#include "aichatdialog.h"
#include "qscrollbar.h"
#include "ui_aichatdialog.h"
#include"../widget/chatframe.h"
#include <usermgr.h>

AIChatDialog::AIChatDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::AIChatDialog)
{
    ui->setupUi(this);
    ui->listWidget->verticalScrollBar()->setSingleStep(20);

    xunfei = new QNetworkAccessManager(this);
    xunfeinet.setUrl(QUrl("https://spark-api-open.xf-yun.com/v1/chat/completions"));
    xunfeinet.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    xunfeinet.setRawHeader("Authorization","Bearer ee5240895053f3173d2cea06d4da9e2e:MTM3OTUyNjVjMWNiOTE5ZGVlMDczZDQ5");

    timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &AIChatDialog::slot_stream_output);
}

AIChatDialog::~AIChatDialog()
{
    delete ui;
}

void AIChatDialog::addChatFrame(const QString &sender, const QString &text, const UserType &type, const NewsType &nt, bool b)
{
    //如果项的父指针是QListWidget 就无法指定位置插入
    ChatFrame *f = new ChatFrame(sender, text, type, nt, ui->listWidget);
    QListWidgetItem *item = new QListWidgetItem();

    connect(f, &ChatFrame::InterfaceUpdate, this, [item](const QSize& size){
        item->setSizeHint(size);
    });
    item->setSizeHint(f->sizeHint());

    if (b)ui->listWidget->insertItem(0, item);
    else {
        ui->listWidget->addItem(item);
    }
    ui->listWidget->setItemWidget(item, f);
}

void AIChatDialog::keyPressEvent(QKeyEvent *event)
{
    if (event->modifiers() == Qt::AltModifier ){
        if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
            on_pushButton_clicked();
        }
    }
    QWidget::keyPressEvent(event);
}

void AIChatDialog::on_pushButton_clicked()
{
    if (!isFinish || !isRequestFinish) return;
    QNetworkReply *reply = xunfei->post(xunfeinet, jsonCreate());
    connect(reply, &QIODevice::readyRead, this, [reply, this]() {
        isFinish = false;
        isRequestFinish = false;
        QByteArray data = reply->readAll();
        processStreamData(data);
    });
    connect(reply, &QNetworkReply::finished, this, [reply, this]() {
        isRequestFinish = true;
        qDebug() << "请求完成";
        reply->deleteLater();
    });
    timer->start(40);

    addChatFrame(UserMgr::GetInstance()->getName(), ui->textEdit->toPlainText(), UserType::Current_User, NewsType::text, false);
    ui->textEdit->clear();

    dialogBox = new AIDialogBoxWid(ui->listWidget);

    // dialogBox->setText("纳法撒旦看风景解幅度萨芬即可飞机卡拉打赏尽快立法放开绿灯撒加分类");
    QListWidgetItem *item = new QListWidgetItem();
    connect(dialogBox, &AIDialogBoxWid::sig_size_hint, this, [item](const int h){
        item->setSizeHint(QSize(100, h + 20));
    });
    item->setSizeHint(dialogBox->sizeHint());
    ui->listWidget->addItem(item);
    ui->listWidget->setItemWidget(item, dialogBox);
}

void AIChatDialog::slot_stream_output()
{
    if (textIndex >= textChunks.size()){
        return;
    }

    QChar c = textChunks[textIndex++];
    nowText += c;
    // ui->textBrowser->setMarkdown(nowText);
    dialogBox->setText(nowText);

    // // 动态调整高度
    // int newHeight = ui->textBrowser->document()->size().rheight();
    // if (newHeight != ui->textBrowser->height()) {
    //     ui->textBrowser->setFixedHeight(newHeight);
    // }

    if (textIndex >= textChunks.size() && isRequestFinish){
        nowText = "";
        isFinish = true;
        qDebug() << "完成";
        timer->stop();
    }
}

void AIChatDialog::processStreamData(const QByteArray& data)
{
    // 提取 JSON 部分
    QString jsonPart = data.mid(6);
    QJsonDocument doc = QJsonDocument::fromJson(jsonPart.toUtf8());
    if (!doc.isObject()) {
        int index = jsonPart.indexOf("data: [DONE]");
        if (index != -1) {
            jsonPart.remove(index, QString("data: [DONE]").length());
        }
        doc = QJsonDocument::fromJson(jsonPart.toUtf8());
        if (!doc.isObject()){
            qDebug() << doc;
            return;
        }
    }

    QJsonObject obj = doc.object();
    QJsonArray choices = obj.value("choices").toArray();
    if (choices.isEmpty()) return;

    QJsonObject delta = choices[0].toObject().value("delta").toObject();
    QString content = delta.value("content").toString();
    if (!content.isEmpty()) {
        textChunks += content;
        qDebug() << content;
    }
}

QByteArray AIChatDialog::jsonCreate()
{
    // 构建 JSON 对象
    QJsonObject rootObject;
    rootObject.insert("model", "lite"); // "model": "lite"
    rootObject.insert("urer", "111");  // "urer": "111"
    QJsonArray messagesArray;
    QJsonObject messageObject;
    messageObject.insert("role", "user");       // "role": "user"
    messageObject.insert("content", ui->textEdit->toPlainText()); // "content": "...内容..."
    messagesArray.append(messageObject);
    rootObject.insert("messages", messagesArray); // "messages": [...]
    rootObject.insert("stream", true);
    QJsonDocument jsonDoc(rootObject);
    QString jsonString = jsonDoc.toJson(QJsonDocument::Indented); // 美化格式化
    qDebug() << jsonString;
    QByteArray jsonData = jsonDoc.toJson();
    return jsonData;
}


